Popular Searches
Popular Course Categories
Popular Courses

JSON Data

Data-Driven Testing

JSON Data in Selenium Automation

JSON (JavaScript Object Notation) is a lightweight, text-based data format commonly used to store and exchange structured information. In Selenium automation frameworks, JSON is especially useful for maintaining external test data such as usernames, passwords, search keywords, product details, user roles, URLs, expected results, and other test inputs.

Using JSON as an external test-data source helps separate test logic from test data. This makes data-driven Selenium frameworks easier to maintain, reuse, scale, and update. JSON is also useful when test data contains nested or structured objects that are less convenient to represent in simple tabular formats.

In a Java + Selenium + TestNG framework, JSON data can be read using libraries such as Jackson or Gson, converted into Java objects or collections, and then supplied to TestNG tests through a @DataProvider. :contentReference[oaicite:0]{index=0}

Course Resource: Selenium Training | Register for Course Demo


1. What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight format used to represent structured data using objects, arrays, key-value pairs, strings, numbers, booleans, and null values.

Although JSON originated from the JavaScript ecosystem, it is language-independent and can be processed by Java, Python, JavaScript, C#, PHP, and many other programming languages.

{

  "username": "admin",

  "password": "admin123",

  "role": "Admin"

}

In this example, username, password, and role are keys, while their corresponding values are strings.


2. Why is JSON Important in Selenium Automation?

JSON is useful in Selenium because automation tests frequently need many different input combinations. Instead of placing all test data directly inside Java test classes, the data can be maintained in JSON files.

  • Separates test data from test logic.
  • Supports data-driven testing.
  • Provides a readable structure for test data.
  • Supports nested and hierarchical data.
  • Can be reused by multiple test classes.
  • Works well with TestNG Data Providers.
  • Can be used with Selenium WebDriver.
  • Can store expected results along with input values.
  • Can be integrated with Maven and CI/CD pipelines.
  • Can be mapped directly to Java objects using JSON libraries.


3. JSON Data Flow in Selenium

A typical JSON-based data-driven Selenium framework follows this flow:

JSON Test Data

      |

      v

JSON File

      |

      v

JSON Parser

      |

      v

Java Object / Map / JsonNode

      |

      v

TestNG @DataProvider

      |

      v

@Test Method

      |

      v

Selenium WebDriver

      |

      v

Application

      |

      v

Assertions

      |

      v

Test Report


4. Basic JSON Structure

A JSON object is enclosed within curly braces { } and contains key-value pairs.

{

  "name": "John",

  "age": 25,

  "active": true

}

JSON supports several common data types.

JSON TypeExample
String"John"
Number25
Booleantrue
Nullnull
Object{ "name": "John" }
Array["Chrome", "Firefox"]


5. JSON Object

A JSON object contains key-value pairs inside curly braces.

{

  "username": "admin",

  "password": "admin123",

  "expected": "Dashboard"

}

This structure is useful for representing one complete test-data record.


6. JSON Array

A JSON array contains multiple values or objects inside square brackets.

[

  "Chrome",

  "Firefox",

  "Edge"

]

For test automation, arrays are commonly used to store multiple test-data records.


7. JSON Array of Test Objects

A very common structure for Selenium data-driven testing is an array containing multiple objects.

[

  {

    "username": "admin",

    "password": "admin123"

  },

  {

    "username": "manager",

    "password": "manager123"

  },

  {

    "username": "employee",

    "password": "employee123"

  }

]

Each object represents one test-data set.

ExecutionUsernamePassword
1adminadmin123
2managermanager123
3employeeemployee123


8. Creating a JSON Test Data File

A JSON test-data file can be stored under the test resources directory.

src

|-- test

    |-- java

    |   |-- tests

    |-- resources

        |-- testdata

            |-- loginData.json

Example loginData.json:

[

  {

    "username": "admin",

    "password": "admin123",

    "expected": "Dashboard"

  },

  {

    "username": "manager",

    "password": "manager123",

    "expected": "Dashboard"

  },

  {

    "username": "invalid",

    "password": "wrong123",

    "expected": "Login Error"

  }

]


9. JSON Data for Login Testing

Login automation is one of the most common applications of JSON-based test data.

[

  {

    "username": "admin",

    "password": "admin123",

    "expected": "success"

  },

  {

    "username": "manager",

    "password": "manager123",

    "expected": "success"

  },

  {

    "username": "invalid",

    "password": "wrong123",

    "expected": "failure"

  }

]

The same Selenium login workflow can then be executed against every JSON record.


10. JSON Data for Search Testing

JSON can store multiple search keywords for data-driven search testing.

[

  {

    "keyword": "Laptop",

    "expectedResult": "Laptop"

  },

  {

    "keyword": "Mobile",

    "expectedResult": "Mobile"

  },

  {

    "keyword": "Headphones",

    "expectedResult": "Headphones"

  }

]


11. JSON Data for Registration Testing

Registration forms usually contain multiple fields. JSON allows all fields to be grouped into one test-data object.

[

  {

    "firstName": "John",

    "lastName": "Smith",

    "email": "[email protected]",

    "mobile": "9876543210"

  },

  {

    "firstName": "David",

    "lastName": "Brown",

    "email": "[email protected]",

    "mobile": "9876543211"

  }

]


12. JSON Data for E-Commerce Testing

E-commerce tests can use JSON for products, quantities, prices, discount codes, categories, and expected results.

[

  {

    "product": "Laptop",

    "quantity": 1,

    "category": "Electronics"

  },

  {

    "product": "Headphones",

    "quantity": 2,

    "category": "Accessories"

  }

]


13. Nested JSON Data

One advantage of JSON is that it can represent hierarchical data.

{

  "user": {

    "name": "John",

    "role": "Admin"

  },

  "address": {

    "city": "Mumbai",

    "country": "India"

  }

}

This structure can be useful when a test requires related information grouped together.


14. JSON Arrays Inside Objects

JSON can contain arrays inside objects.

{

  "username": "admin",

  "roles": [

    "Admin",

    "Manager"

  ],

  "permissions": [

    "read",

    "write",

    "delete"

  ]

}

Such structures are useful for testing applications with multiple roles, permissions, products, or selections.


15. JSON Objects Inside Arrays

An array can contain multiple complex objects.

{

  "users": [

    {

      "name": "John",

      "role": "Admin"

    },

    {

      "name": "David",

      "role": "Manager"

    },

    {

      "name": "Robert",

      "role": "Employee"

    }

  ]

}


16. Reading JSON in Java

Java does not provide a general-purpose JSON object model in the core language, so Selenium frameworks commonly use third-party JSON libraries such as Jackson or Gson.

Jackson provides classes such as ObjectMapper and JsonNode for parsing JSON. Gson provides APIs for converting JSON into Java objects, collections, and other structures. :contentReference[oaicite:1]{index=1}


17. Using Jackson for JSON Parsing

Jackson is a popular Java library for reading JSON and mapping JSON content to Java objects.

For a Maven project, a Jackson dependency can be added to pom.xml.

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.17.0</version>

    <scope>test</scope>

</dependency>

The exact library version should be selected according to the project's dependency-management and compatibility requirements. :contentReference[oaicite:2]{index=2}


18. Reading JSON with Jackson ObjectMapper

The ObjectMapper class can read a JSON file and convert its contents into a JSON tree.

import com.fasterxml.jackson.databind.JsonNode;

import com.fasterxml.jackson.databind.ObjectMapper;

 

import java.io.File;

 

public class JsonReader {

 

    public static void main(String[] args) throws Exception {

 

        ObjectMapper mapper = new ObjectMapper();

 

        JsonNode root = mapper.readTree(

            new File("src/test/resources/testdata/loginData.json")

        );

 

        System.out.println(root);

    }

}


19. Reading JSON Objects with JsonNode

When the JSON contains an array of objects, Jackson's JsonNode API can be used to iterate through the records.

ObjectMapper mapper = new ObjectMapper();

 

JsonNode root = mapper.readTree(

    new File("src/test/resources/testdata/loginData.json")

);

 

for (JsonNode node : root) {

    String username = node.get("username").asText();

    String password = node.get("password").asText();

 

    System.out.println(username);

    System.out.println(password);

}


20. JSON with TestNG DataProvider

A common Selenium architecture is to read JSON data inside a TestNG @DataProvider and return one row for each test invocation.

import com.fasterxml.jackson.databind.JsonNode;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

import java.io.File;

 

public class LoginTest {

 

    @DataProvider(name = "loginData")

    public Object[][] loginData() throws Exception {

 

        ObjectMapper mapper = new ObjectMapper();

 

        JsonNode root = mapper.readTree(

            new File("src/test/resources/testdata/loginData.json")

        );

 

        Object[][] data = new Object[root.size()][3];

 

        for (int i = 0; i < root.size(); i++) {

            JsonNode node = root.get(i);

 

            data[i][0] = node.get("username").asText();

            data[i][1] = node.get("password").asText();

            data[i][2] = node.get("expected").asText();

        }

 

        return data;

    }

 

    @Test(dataProvider = "loginData")

    public void loginTest(

            String username,

            String password,

            String expected) {

 

        System.out.println(username);

        System.out.println(password);

        System.out.println(expected);

    }

}

This pattern connects external JSON data with TestNG's data-driven execution model. :contentReference[oaicite:3]{index=3}


21. JSON DataProvider with Iterator

For larger or dynamically constructed data sets, a Data Provider can return an Iterator<Object[]> instead of directly constructing an Object[][].

import org.testng.annotations.DataProvider;

 

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

 

@DataProvider(name = "jsonData")

public Iterator<Object[]> jsonData() {

 

    List<Object[]> data = new ArrayList<>();

 

    data.add(new Object[]{"admin", "admin123"});

    data.add(new Object[]{"manager", "manager123"});

    data.add(new Object[]{"employee", "employee123"});

 

    return data.iterator();

}


22. Using Gson for JSON Parsing

Gson is another commonly used Java library for converting JSON data into Java objects and collections.

import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;

 

import java.io.FileReader;

import java.lang.reflect.Type;

import java.util.List;

import java.util.Map;

 

public class GsonExample {

 

    public static void main(String[] args) throws Exception {

 

        Gson gson = new Gson();

 

        Type type = new TypeToken<List<Map<String, String>>>() {}.getType();

 

        List<Map<String, String>> data =

            gson.fromJson(

                new FileReader("src/test/resources/testdata/loginData.json"),

                type

            );

 

        for (Map<String, String> row : data) {

            System.out.println(row.get("username"));

        }

    }

}

Gson can also be used to transform JSON collections into data structures that can later be supplied to TestNG. :contentReference[oaicite:4]{index=4}


23. JSON to Java POJO

A POJO (Plain Old Java Object) can represent one JSON record. This approach makes test data strongly structured and easier to work with in larger frameworks.

public class LoginData {

 

    private String username;

    private String password;

    private String expected;

 

    public String getUsername() {

        return username;

    }

 

    public String getPassword() {

        return password;

    }

 

    public String getExpected() {

        return expected;

    }

}


24. Mapping JSON to POJO with Jackson

Jackson can deserialize JSON objects into Java POJOs.

ObjectMapper mapper = new ObjectMapper();

 

LoginData data = mapper.readValue(

    new File("src/test/resources/testdata/login.json"),

    LoginData.class

);

 

System.out.println(data.getUsername());

System.out.println(data.getExpected());

For arrays or lists of objects, Jackson can map JSON into collections of POJOs as well.


25. JSON List of POJOs

Suppose the JSON file contains multiple login records:

[

  {

    "username": "admin",

    "password": "admin123",

    "expected": "Dashboard"

  },

  {

    "username": "manager",

    "password": "manager123",

    "expected": "Dashboard"

  }

]

It can be mapped to a Java list.

List<LoginData> users = mapper.readValue(

    new File("src/test/resources/testdata/loginData.json"),

    mapper.getTypeFactory().constructCollectionType(

        List.class,

        LoginData.class

    )

);


26. JSON DataProvider Using POJO

A POJO-based Data Provider provides a clean separation between JSON parsing and test execution.

@DataProvider(name = "loginData")

public Object[][] loginData() throws Exception {

 

    ObjectMapper mapper = new ObjectMapper();

 

    List<LoginData> users = mapper.readValue(

        new File("src/test/resources/testdata/loginData.json"),

        mapper.getTypeFactory().constructCollectionType(

            List.class,

            LoginData.class

        )

    );

 

    Object[][] data = new Object[users.size()][1];

 

    for (int i = 0; i < users.size(); i++) {

        data[i][0] = users.get(i);

    }

 

    return data;

}

 

@Test(dataProvider = "loginData")

public void loginTest(LoginData data) {

    System.out.println(data.getUsername());

}


27. JSON Data with Selenium WebDriver

JSON becomes especially useful when combined with Selenium WebDriver for data-driven UI automation.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class JsonLoginTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com/login");

    }

 

    @DataProvider(name = "loginData")

    public Object[][] loginData() {

        return new Object[][] {

            {"admin", "admin123"},

            {"manager", "manager123"},

            {"employee", "employee123"}

        };

    }

 

    @Test(dataProvider = "loginData")

    public void loginTest(String username, String password) {

 

        driver.findElement(By.id("username"))

                .sendKeys(username);

 

        driver.findElement(By.id("password"))

                .sendKeys(password);

 

        driver.findElement(By.id("loginButton"))

                .click();

 

        Assert.assertTrue(

            driver.getTitle().contains("Dashboard")

        );

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}

In a production framework, the values in the Data Provider can be loaded dynamically from the JSON file rather than being hard-coded.


28. JSON Data for Positive and Negative Testing

JSON can contain both valid and invalid test scenarios.

[

  {

    "username": "validUser",

    "password": "validPass",

    "expected": "Dashboard"

  },

  {

    "username": "invalidUser",

    "password": "validPass",

    "expected": "Invalid Username"

  },

  {

    "username": "validUser",

    "password": "invalidPass",

    "expected": "Invalid Password"

  },

  {

    "username": "",

    "password": "",

    "expected": "Required Fields"

  }

]

This makes JSON useful for positive, negative, boundary, and validation scenarios.


29. JSON Data for Browser Testing

Browser configuration can also be represented in JSON when the framework is designed to load execution settings externally.

[

  {

    "browser": "chrome",

    "url": "https://example.com"

  },

  {

    "browser": "firefox",

    "url": "https://example.com"

  },

  {

    "browser": "edge",

    "url": "https://example.com"

  }

]


30. JSON Data for Environment Testing

Different environments can be represented using JSON.

[

  {

    "environment": "QA",

    "url": "https://qa.example.com"

  },

  {

    "environment": "Stage",

    "url": "https://stage.example.com"

  },

  {

    "environment": "Production",

    "url": "https://www.example.com"

  }

]

This allows a framework to load environment-specific configuration without changing the test logic.


31. JSON Data for User Roles

Role-based testing can use JSON to represent different users and permissions.

[

  {

    "username": "adminUser",

    "role": "Admin"

  },

  {

    "username": "managerUser",

    "role": "Manager"

  },

  {

    "username": "employeeUser",

    "role": "Employee"

  }

]


32. JSON Data for Search Filters

[

  {

    "keyword": "Laptop",

    "category": "Electronics",

    "expected": "Laptop"

  },

  {

    "keyword": "Shoes",

    "category": "Fashion",

    "expected": "Shoes"

  },

  {

    "keyword": "Book",

    "category": "Books",

    "expected": "Book"

  }

]


33. JSON Data with Expected Results

Expected values can be stored together with input values.

[

  {

    "input": "10",

    "expected": "100"

  },

  {

    "input": "20",

    "expected": "400"

  },

  {

    "input": "30",

    "expected": "900"

  }

]

The test can read both the input and expected result and then use an assertion.


34. JSON Data and Assertions

@DataProvider(name = "calculatorData")

public Object[][] calculatorData() {

    return new Object[][] {

        {10, 100},

        {20, 400},

        {30, 900}

    };

}

 

@Test(dataProvider = "calculatorData")

public void calculatorTest(int input, int expected) {

 

    int actual = input * input;

 

    Assert.assertEquals(actual, expected);

}

When the same data is loaded from JSON, the test method can remain unchanged while the external test data changes.


35. JSON Data and Page Object Model

JSON works well with the Page Object Model (POM). JSON manages test data, the test class manages test execution, and page classes manage Selenium interactions.

JSON File

    |

    v

Data Provider

    |

    v

Test Class

    |

    v

Page Object

    |

    v

WebDriver

    |

    v

Application

This separation improves framework organization and maintainability.


36. JSON with Login Page Object

public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    private By loginButton =

        By.id("loginButton");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void login(String user, String pass) {

        driver.findElement(username)

                .sendKeys(user);

 

        driver.findElement(password)

                .sendKeys(pass);

 

        driver.findElement(loginButton)

                .click();

    }

}

The JSON Data Provider can supply the username and password while the page class handles the browser interaction.


37. JSON Data Provider with POM

@Test(dataProvider = "loginData")

public void loginTest(LoginData data) {

 

    LoginPage loginPage =

        new LoginPage(driver);

 

    loginPage.login(

        data.getUsername(),

        data.getPassword()

    );

}

This keeps test data, test logic, and page interaction responsibilities separate.


38. JSON vs Excel vs CSV

FeatureJSONExcelCSV
Structured DataExcellentGoodLimited
Nested DataExcellentLimitedNo
Simple Tabular DataGoodExcellentExcellent
Human ReadabilityHighHighHigh
Java ParsingJackson/GsonApache POICSV libraries
Best UseStructured test dataSpreadsheet-based dataSimple tabular data

JSON is particularly useful when test data has nested or structured relationships rather than only simple rows and columns. :contentReference[oaicite:5]{index=5}


39. JSON vs Hard-Coded Test Data

Hard-Coded DataJSON Data
Data is inside Java codeData is stored externally
Code changes may be requiredData can often be changed independently
Less reusableMore reusable
Can become difficult to maintainEasier to organize large data sets
Limited structureSupports nested structure


40. JSON Data and TestNG DataProvider

The most common architecture for JSON-based data-driven Selenium testing is:

loginData.json

      |

      v

JSON Reader

      |

      v

Java Objects

      |

      v

@DataProvider

      |

      v

@Test(dataProvider = "loginData")

      |

      v

Login Test

      |

      v

Selenium WebDriver

TestNG Data Providers are designed to supply test data to test methods, making them a natural integration point for JSON test data. :contentReference[oaicite:6]{index=6}


41. External JSON Data Reader

For a reusable framework, JSON parsing can be moved into a utility class.

public class JsonReader {

 

    private final ObjectMapper mapper =

        new ObjectMapper();

 

    public JsonNode readJson(String filePath)

            throws Exception {

 

        return mapper.readTree(

            new File(filePath)

        );

    }

}

The Data Provider can then use the utility instead of containing all JSON parsing logic itself.


42. Reusable JSON Data Utility

public class JsonUtils {

 

    public static JsonNode read(String path)

            throws Exception {

 

        ObjectMapper mapper =

            new ObjectMapper();

 

        return mapper.readTree(

            new File(path)

        );

    }

}

Reusable utilities are helpful when multiple test classes use different JSON files.


43. Filtering JSON Test Data

Sometimes a JSON file contains many records but a particular test needs only a subset of them. The framework can filter records based on fields such as test case, environment, browser, role, or execution flag.

[

  {

    "testCase": "TC001",

    "browser": "chrome",

    "execute": true

  },

  {

    "testCase": "TC002",

    "browser": "firefox",

    "execute": false

  },

  {

    "testCase": "TC003",

    "browser": "edge",

    "execute": true

  }

]

A JSON reader can select only records where execute is true.


44. JSON Data with Execution Flags

Execution flags can help control which test-data records should be used.

[

  {

    "username": "admin",

    "password": "admin123",

    "execute": true

  },

  {

    "username": "manager",

    "password": "manager123",

    "execute": false

  }

]

The Data Provider can filter records before returning them to TestNG.


45. JSON Data with Test Case IDs

Adding a test-case identifier makes debugging and reporting easier.

[

  {

    "testCaseId": "LOGIN_001",

    "username": "admin",

    "password": "admin123",

    "expected": "Dashboard"

  },

  {

    "testCaseId": "LOGIN_002",

    "username": "invalid",

    "password": "wrong123",

    "expected": "Login Error"

  }

]

The test case ID can be logged whenever a test is executed or fails.


46. JSON Data with Test Names

[

  {

    "testName": "Valid Admin Login",

    "username": "admin",

    "password": "admin123"

  },

  {

    "testName": "Invalid Login",

    "username": "invalid",

    "password": "wrong123"

  }

]

Meaningful metadata makes large data-driven suites easier to understand.


47. JSON Data and Parallel Execution

TestNG Data Providers can be configured for parallel execution. This can be useful when a JSON file contains many independent test-data records.

@DataProvider(

    name = "jsonData",

    parallel = true

)

public Object[][] jsonData() {

    return new Object[][] {

        {"user1"},

        {"user2"},

        {"user3"},

        {"user4"}

    };

}

When parallel execution is used with Selenium, WebDriver instances and other shared framework resources must be isolated or made thread-safe.


48. JSON Data and Thread Safety

Parallel data-driven Selenium tests should generally use independent WebDriver instances for independent test invocations.

JSON Data

    |

    +---- Test 1 ---- WebDriver 1

    |

    +---- Test 2 ---- WebDriver 2

    |

    +---- Test 3 ---- WebDriver 3

    |

    +---- Test 4 ---- WebDriver 4

A single shared WebDriver instance should not be used unsafely by concurrent tests.


49. JSON Data and Maven

JSON-based Selenium tests can be executed through Maven like other TestNG tests.

mvn test

Maven manages project dependencies such as Selenium, TestNG, Jackson, and other required libraries.


50. JSON Data in CI/CD

JSON test data can be used in CI/CD pipelines to execute the same automation suite against different data sets.

Developer Commit

      |

      v

CI/CD Pipeline

      |

      v

Maven Build

      |

      v

TestNG

      |

      v

JSON Reader

      |

      v

@DataProvider

      |

      v

Selenium Tests

      |

      v

Reports

This design helps keep test logic stable while test data can be maintained independently.


51. JSON Data and Environment Variables

JSON can contain non-sensitive configuration values, but secrets such as passwords, API keys, access tokens, and private credentials should not normally be stored as plain text in source-controlled JSON files.

A framework can combine JSON test data with environment variables or an appropriate secret-management solution.

{

  "username": "testUser",

  "environment": "QA"

}

Credentials can then be obtained securely at runtime rather than being committed to the repository.


52. JSON Data for API and UI Testing

JSON is particularly useful in automation frameworks that test both APIs and web interfaces because JSON is commonly used as an API data format as well as a structured test-data format.

JSON Test Data

      |

      +------> API Test

      |

      +------> Selenium UI Test

This allows common business test data to be reused across different layers when the data model is appropriate.


53. JSON Data with API Response Testing

JSON can also be used to store expected API response values.

{

  "endpoint": "/users",

  "expectedStatus": 200,

  "expectedUser": "admin"

}

The same JSON-based test-data strategy can therefore support UI and API automation.


54. JSON Data Validation

JSON test-data files should be valid before the automation suite begins execution. Invalid JSON can cause parsing failures before the actual Selenium test starts.

Common JSON syntax requirements include:

  • Keys should be enclosed in double quotes.
  • String values should use double quotes.
  • Objects use curly braces.
  • Arrays use square brackets.
  • Key-value pairs use a colon.
  • Items are separated by commas.
  • JSON does not support trailing commas in standard JSON syntax.


55. Common JSON Syntax Mistakes

Incorrect:

{

  username: "admin",

  password: "admin123",

}

Correct:

{

  "username": "admin",

  "password": "admin123"

}


56. Handling Missing JSON Fields

Test frameworks should define how missing fields are handled. Depending on the JSON library and mapping approach, a missing property may result in a null value, a default value, or a mapping/validation error.

{

  "username": "admin"

}

If the test requires both username and password, the data validation layer should detect the missing password before executing the Selenium workflow.


57. Handling Null JSON Values

JSON supports the null value.

{

  "username": "admin",

  "password": null

}

Automation code should handle null values intentionally rather than allowing unexpected NullPointerExceptions or invalid browser actions.


58. JSON Data Validation Utility

public static void validateLoginData(

        String username,

        String password) {

 

    if (username == null || username.isBlank()) {

        throw new IllegalArgumentException(

            "Username is required"

        );

    }

 

    if (password == null || password.isBlank()) {

        throw new IllegalArgumentException(

            "Password is required"

        );

    }

}


59. Practical Project Structure

A scalable Selenium framework can organize JSON data, utilities, page classes, and tests separately.

src

|-- test

    |-- java

    |   |-- tests

    |   |   |-- LoginTest.java

    |   |   |-- SearchTest.java

    |   |   |-- CheckoutTest.java

    |   |

    |   |-- pages

    |   |   |-- LoginPage.java

    |   |   |-- SearchPage.java

    |   |   |-- CheckoutPage.java

    |   |

    |   |-- data

    |   |   |-- LoginData.java

    |   |   |-- SearchData.java

    |   |

    |   |-- utilities

    |       |-- JsonUtils.java

    |       |-- DriverFactory.java

    |       |-- ConfigReader.java

    |

    |-- resources

        |-- testdata

            |-- loginData.json

            |-- searchData.json

            |-- checkoutData.json


60. Complete Practical JSON Login Example

The following example demonstrates the overall concept of using JSON data with a Selenium TestNG login test.

loginData.json

[

  {

    "username": "admin",

    "password": "admin123",

    "expected": "Dashboard"

  },

  {

    "username": "manager",

    "password": "manager123",

    "expected": "Dashboard"

  },

  {

    "username": "invalid",

    "password": "wrong123",

    "expected": "Login Error"

  }

]

LoginData.java

public class LoginData {

 

    private String username;

    private String password;

    private String expected;

 

    public String getUsername() {

        return username;

    }

 

    public String getPassword() {

        return password;

    }

 

    public String getExpected() {

        return expected;

    }

}

LoginTest.java

import com.fasterxml.jackson.databind.ObjectMapper;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.*;

 

import java.io.File;

import java.util.List;

 

public class LoginTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com/login");

    }

 

    @DataProvider(name = "loginData")

    public Object[][] loginData() throws Exception {

 

        ObjectMapper mapper = new ObjectMapper();

 

        List<LoginData> users = mapper.readValue(

            new File(

                "src/test/resources/testdata/loginData.json"

            ),

            mapper.getTypeFactory().constructCollectionType(

                List.class,

                LoginData.class

            )

        );

 

        Object[][] data = new Object[users.size()][1];

 

        for (int i = 0; i < users.size(); i++) {

            data[i][0] = users.get(i);

        }

 

        return data;

    }

 

    @Test(dataProvider = "loginData")

    public void loginTest(LoginData data) {

 

        driver.findElement(By.id("username"))

                .sendKeys(data.getUsername());

 

        driver.findElement(By.id("password"))

                .sendKeys(data.getPassword());

 

        driver.findElement(By.id("loginButton"))

                .click();

 

        String actualTitle = driver.getTitle();

 

        System.out.println(

            "Expected: " + data.getExpected()

        );

 

        System.out.println(

            "Actual Title: " + actualTitle

        );

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}


61. Complete JSON Data-Driven Architecture

                 JSON Files

                     |

          +----------+----------+

          |          |          |

       Login       Search     Product

          |          |          |

          +----------+----------+

                     |

                     v

                JsonUtils

                     |

                     v

               Java Objects

                     |

                     v

               DataProvider

                     |

                     v

                Test Classes

                     |

                     v

                Page Objects

                     |

                     v

              Selenium WebDriver

                     |

                     v

                Application

                     |

                     v

                 Assertions

                     |

                     v

                  Reports


62. Advantages of JSON Data

  • Readable: JSON is relatively easy for humans to understand.
  • Structured: It supports objects, arrays, and nested structures.
  • Reusable: The same JSON data can be used by multiple tests.
  • Maintainable: Test data can be separated from Java test logic.
  • Scalable: Additional records can be added without creating new test methods.
  • Flexible: It supports strings, numbers, booleans, arrays, objects, and null values.
  • Framework Friendly: It works well with TestNG Data Providers.
  • Library Support: Java libraries such as Jackson and Gson provide JSON parsing capabilities.
  • API Friendly: JSON can be reused for API and UI automation scenarios.
  • CI/CD Friendly: JSON files can be included in automated test execution workflows.


63. Limitations of JSON Data

  • Very large JSON files can become difficult to maintain.
  • Incorrect JSON syntax can prevent test execution.
  • Additional parsing libraries are generally required in Java projects.
  • Complex JSON structures may require additional mapping classes.
  • Secrets should not be stored as plain text in source-controlled JSON files.
  • Large data sets may require careful memory management.
  • Parallel execution still requires thread-safe Selenium framework design.


64. JSON vs TestNG @DataProvider

FeatureJSON@DataProvider
PurposeStores test dataSupplies data to test methods
LocationExternal fileJava method
Data StorageObjects and arraysObject[][] or other supported return forms
ReusableYesYes
External DataYesCan consume external data
Typical CombinationJSON stores dataDataProvider supplies data


65. JSON vs Properties File

JSONProperties
Supports nested structuresPrimarily key-value configuration
Supports arraysDoes not naturally represent arrays
Useful for complex test dataUseful for simple configuration
Can represent multiple recordsUsually represents individual configuration values
Common for test dataCommon for environment/configuration settings


66. Common Mistakes with JSON Data

  • Using invalid JSON syntax.
  • Using single quotes instead of standard JSON double quotes.
  • Forgetting commas between properties.
  • Using trailing commas.
  • Using incorrect JSON field names in Java code.
  • Not handling null or missing values.
  • Using incorrect file paths.
  • Not adding the required JSON parsing dependency.
  • Mixing test logic into the JSON parsing utility.
  • Hard-coding passwords or secrets in JSON files.
  • Not validating test data before execution.
  • Sharing unsafe WebDriver instances during parallel execution.


67. Best Practices for JSON Data

  • Keep JSON files under an appropriate test resources directory.
  • Use meaningful and consistent property names.
  • Keep test data separate from Selenium interaction logic.
  • Use POJOs for complex and strongly structured data.
  • Use a reusable JSON utility for common parsing operations.
  • Use TestNG Data Providers to connect JSON data with tests.
  • Include test case IDs for traceability.
  • Include expected results when appropriate.
  • Validate required fields before running browser actions.
  • Keep sensitive credentials outside source-controlled JSON files.
  • Use external data files for large or frequently changing test data.
  • Use parallel execution only when WebDriver and framework resources are thread-safe.


68. Practical Exercises

  1. Create a JSON file containing five username and password combinations.
  2. Read the JSON file using Jackson.
  3. Create a TestNG Data Provider using the JSON records.
  4. Execute a Selenium login test for every JSON record.
  5. Add expected login results to the JSON file.
  6. Create JSON data for five search keywords.
  7. Create JSON data for multiple user roles.
  8. Create JSON data for browser and environment combinations.
  9. Create a POJO for a JSON test-data object.
  10. Build a reusable JsonUtils class.
  11. Connect JSON data with a Page Object Model framework.
  12. Execute JSON-based tests in parallel using a thread-safe driver design.


69. Interview Questions on JSON Data

1. What is JSON?

JSON is a lightweight data-interchange format used to represent structured data using objects, arrays, and key-value pairs.

2. Why is JSON useful in Selenium automation?

It can store external test data separately from Selenium test logic and can support data-driven testing.

3. Which Java libraries can parse JSON?

Popular choices include Jackson and Gson.

4. What is ObjectMapper?

ObjectMapper is a Jackson class used to read, parse, serialize, and deserialize JSON data.

5. What is JsonNode?

JsonNode is Jackson's tree-model representation of JSON data.

6. What is a JSON object?

A JSON object is a collection of key-value pairs enclosed in curly braces.

7. What is a JSON array?

A JSON array is an ordered collection of values or objects enclosed in square brackets.

8. Can JSON contain nested objects?

Yes. JSON supports nested objects and arrays.

9. How can JSON be used with TestNG?

JSON can be read by Java code and the resulting records can be returned through a TestNG Data Provider.

10. Can JSON be used with Page Object Model?

Yes. JSON can provide test data while Page Objects manage Selenium interactions.

11. Can JSON contain expected results?

Yes. Expected values can be stored as properties in each test-data object.

12. Can JSON data be used for negative testing?

Yes. Invalid usernames, passwords, search values, empty fields, and other negative scenarios can be stored in JSON.

13. What is a POJO?

A POJO is a normal Java class that can represent structured application or test data.

14. Why use POJOs with JSON?

POJOs provide a strongly structured and readable way to work with complex JSON records.

15. Can JSON be used for API testing?

Yes. JSON is commonly used for API requests, responses, and API test data.

16. What is the difference between JSON and Excel?

Excel is convenient for spreadsheet-style data, while JSON is particularly useful for structured and nested data.

17. Can JSON Data Providers run in parallel?

Yes. If the TestNG Data Provider is configured for parallel execution, its invocations can run concurrently, provided the framework is thread-safe.

18. Should passwords be stored in JSON?

Plain-text passwords and other secrets should generally not be stored in source-controlled JSON files.

19. What happens if JSON syntax is invalid?

The JSON parser can fail before the test executes, so the test-data file should be validated.

20. What is the main benefit of JSON-based data-driven testing?

It allows test logic to remain reusable while test data can be maintained externally and supplied dynamically to the automation tests.


70. Quick Reference Table

ConceptDescription
JSONStructured text-based data format
JSON ObjectCollection of key-value pairs
JSON ArrayCollection of values or objects
ObjectMapperJackson class used for JSON processing
JsonNodeJackson JSON tree representation
GsonJava library for JSON serialization/deserialization
POJOJava object representing structured data
@DataProviderTestNG mechanism for supplying test data
POMDesign pattern for separating page interactions from tests
JSON UtilityReusable component for reading and parsing JSON


71. Learning Roadmap for JSON Data in Selenium

  1. Learn basic JSON syntax.
  2. Understand JSON objects and arrays.
  3. Create JSON test-data files.
  4. Learn Java file handling.
  5. Learn Jackson or Gson.
  6. Read JSON using ObjectMapper.
  7. Work with JsonNode.
  8. Convert JSON into Java collections.
  9. Convert JSON into POJOs.
  10. Connect JSON with TestNG @DataProvider.
  11. Use JSON data in Selenium login testing.
  12. Use JSON with Page Object Model.
  13. Add expected results and assertions.
  14. Build reusable JSON utilities.
  15. Use JSON in Maven and CI/CD automation.
  16. Implement safe parallel execution.


72. Summary

JSON is a powerful format for storing structured test data in Selenium automation frameworks. It allows test data to be maintained separately from Java test logic and is especially useful when test data contains multiple records, nested objects, arrays, or other structured relationships.

In a Java + Selenium + TestNG framework, JSON can be parsed using libraries such as Jackson or Gson. The parsed records can then be supplied through TestNG @DataProvider methods and consumed by Selenium test methods. :contentReference[oaicite:7]{index=7}

For larger frameworks, JSON can be combined with POJOs, Page Object Model, reusable utilities, Maven, CI/CD, assertions, reporting, and parallel execution. This architecture helps create maintainable and scalable data-driven automation suites.


73. Course Resources

Learn more about Selenium automation and related testing concepts:

Final Takeaway: JSON allows Selenium automation frameworks to separate test data from test logic, making data-driven testing more organized, reusable, and scalable. When JSON is combined with TestNG Data Providers and Page Object Model, the same Selenium workflow can be executed against many structured test-data combinations without duplicating test methods.

whatsapp